# src/api/medical_records.py
from fastapi import APIRouter, HTTPException, status, Query
from typing import List
from ..models.schemas import MedicalRecordCreate, MedicalRecordUpdate, MedicalRecordOut
from .. import crud

router = APIRouter(tags=["medical_records"])


@router.post("", response_model=MedicalRecordOut, status_code=status.HTTP_201_CREATED)
def create_record(payload: MedicalRecordCreate):
    try:
        rec = crud.create_medical_record(payload.dict())
        return rec
    except Exception as e:
        # Unique/constraint violations etc.
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/patient/{patient_id}", response_model=List[MedicalRecordOut])
def get_patient_history(patient_id: int, limit: int = Query(50, ge=1, le=500)):
    return crud.get_patient_history(patient_id, limit=limit)


@router.get("/{record_id}", response_model=MedicalRecordOut)
def get_record(record_id: int):
    rec = crud.get_medical_record(record_id)
    if not rec:
        raise HTTPException(status_code=404, detail="Medical record not found")
    return rec


@router.put("/{record_id}", response_model=MedicalRecordOut)
def update_record(record_id: int, payload: MedicalRecordUpdate):
    updated = crud.update_medical_record(record_id, payload.dict(exclude_unset=True))
    if not updated:
        raise HTTPException(status_code=404, detail="Medical record not found or no updates applied")
    return updated


@router.delete("/{record_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_record(record_id: int):
    count = crud.delete_medical_record(record_id)
    if count == 0:
        raise HTTPException(status_code=404, detail="Medical record not found")
    return None
